package com.ezandroid;

import android.app.Application;
import android.content.Context;

import com.ezandroid.library.image.EZImageLoader;
import com.ezandroid.library.network.cache.CacheManager;
import com.ezandroid.library.network.http.request.RequestManager;
import com.ezandroid.library.network.http.ssl.SSLContextFactory;
import com.ezandroid.library.network.http.ssl.TrustedHostnameVerifier;
import com.ezandroid.module.manager.DownControllerManager;
import com.ezandroid.util.CrashHandler;
import com.ezandroid.util.FileUtil;
import com.ezandroid.util.LogUtil;
import com.nostra13.universalimageloader.BuildConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

/**
 * EZAndroidApplication
 *
 * @author like
 * @date 2016-05-13
 */
public class EZAndroidApplication extends Application {

    public static Context gContext;

    @Override
    public void onCreate() {
        super.onCreate();
        gContext = this;
        init();
    }

    private void init() {
        // 设置日志开关
        LogUtil.setLogEnable(BuildConfig.DEBUG);

        // 记录崩溃异常
        CrashHandler crashHandler = new CrashHandler(gContext);
        Thread.setDefaultUncaughtExceptionHandler(crashHandler);

        // 初始化缓存管理器
        CacheManager.getInstance().init(this);

        // 初始化下载管理器
        DownControllerManager.getInstance().registerAll();

        // 初始化图片加载器
        EZImageLoader.init(this, FileUtil.getPathByType(FileUtil.DIR_TYPE_IMAGE));

        // 初始化网络管理器
        RequestManager.getInstance()
                .setClient(getOkHttpClient())
                .setPoolSize(8)
                .init(this);
    }

    private OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(15, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);

        // 配置SSL
        try {
            builder.hostnameVerifier(TrustedHostnameVerifier.getTrustedVerifier());
            SSLContextFactory factory = SSLContextFactory.getInstance();
            builder.sslSocketFactory(factory.makeContext().getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder.build();
    }
}
